import { Form, Input, Select, Row, DatePicker, Col, message, Button, } from 'antd';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import React from 'react'
import BreadcrumbCustom from '../../BreadcrumbCustom'
import moment from 'moment';
import * as Request from '../../../Server/SystemManger';
import * as Utils from '../../../common/utils';
import qs from 'qs'
import * as Constant from '../../../common/const';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const Option = Select.Option;

const formData = {
    "usage": { "title": "报活" },
    "logInstall": { "title": "安装量" },
    "logUninstall": { "title": "卸载量" },
    "mso": { "title": "MSO信息" },
    "updateRequest": { "title": "请求详情" },
    "updateDownload": { "title": "下载详情" },
    "updateInstall": { "title": "安装详情" },
}
const dateFormat = 'YYYY-MM-DD';
const currentDate = new Date();
let sysCompany = {};
let flag = true;
let disState = false;

class ExportForm extends React.Component {
    constructor(props) {
        super(props)
        let user = JSON.parse(localStorage.getItem('user'));
        sysCompany = user.sysCompany;
        flag = Utils.objectIsNull(sysCompany);
        this.state = {
            type: '',
            title: '',
            startIp: flag && sysCompany.startIp, //分部管理起始ip
            endIp: flag && sysCompany.endIp, //分部管理结束ip
            partNameData: [] //分部名数据
        }
    }

    componentWillMount() {
        //获取路径最后一个，判断
        const path = this.props.match.path
        const pathArr = path.split("/")
        const type = pathArr[pathArr.length - 1]
        disState = (type == 'usage' || type == 'mso' || type == 'updateRequest');
        // 设置title
        this.setState({
            type,
            title: formData[type].title
        });
        if(flag) {
            this.getPartName();
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        const { title, startIp, endIp } = this.state;
        this.props.form.validateFieldsAndScroll((err, values) => {
            const date = values['range-picker']
            values.startDate = date[0].format(dateFormat)
            values.endDate = date[1].format(dateFormat)
            values.startIp = values.startIp ? values.startIp : startIp;
            values.endIp = values.endIp ? values.endIp : endIp;
            delete values['range-picker'];
            delete values['partName'];
            if (!err) {
                Request.exportData(this.state.type, qs.stringify(values)).then(res => {
                    const { data, headers } = res;
                    const filenameArray = headers['content-disposition'].split("_");
                    const filename = title + '_' + filenameArray[1] + '_' + filenameArray[2];
                    var blob = new Blob([data], { type: 'application/zip;charset=utf-8' }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
                    Utils.downloadExcel(blob, filename, data);
                })
            }
        });
    }

    disabledDate = (current) => {
        // Can not select days before today and today
        return current.valueOf() > Date.now();
    }

    validateDate = (rule, value, callback) => {
        if ((value[0].month() !== value[1].month()) && disState) {
            callback('不能跨月查询，请选择同一月份内的数据!');
        } else {
            callback()
        }
    }

    //获取分部名数据
    getPartName = () => {
        Request.getClassifiesAll().then(res => {
            if (res && res.code == Constant.REQUEST_SUCCESS) {
                const data = res.data
                this.setState({
                    partNameData: data,
                });
            } else {
                res && res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg);
            }
        });
    }

    //校验起始ip
    checkStartIP = (rule, value, callback) =>{
        let { startIp, endIp } = this.state;
        if(value==''||value==undefined){
            if(sysCompany.id==1){
                callback();
                return ;
            }else{
                callback('请输入起始IP地址！');
                return ;
            }
        }
        if(!Utils.checkIP(value)){
            callback('请输入正确地IP地址！');
            return ;
        }else if(!Utils.checkIPValue(value, startIp, endIp)){
            callback('请输入分部范围内的IP地址！');
            return ;
        }else if(!Utils.checkIPCount(this.props.form.getFieldValue("startIp"),this.props.form.getFieldValue("endIp"))){
            callback('起始IP不能大于结束IP');
            return ;
        }
        if(this.props.form.getFieldValue('endIp') && this.props.form.getFieldError('endIp')){
            this.props.form.validateFields(['endIp'],{ force: true });
        }
        callback();
    }

    //校验结束ip
    checkEndIP = (rule, value, callback) =>{
        let { startIp, endIp } = this.state;
        if(value==''||value==undefined){
            if(sysCompany.id==1){
                callback();
                return ;
            }else{
                callback('请输入结束IP地址！');
                return ;
            }
        }
        if(!Utils.checkIP(value)){
            callback('请输入正确地IP地址！');
            return ;
        }else if(!Utils.checkIPValue(value, startIp, endIp)){
            callback('请输入分部范围内的IP地址！');
            return ;
        }else if(!Utils.checkIPCount(this.props.form.getFieldValue("startIp"),this.props.form.getFieldValue("endIp"))){
            callback('结束IP不能小于起始IP');
            return ;
        }
        if(this.props.form.getFieldValue('startIp') && this.props.form.getFieldError('startIp')){
            this.props.form.validateFields(['startIp'],{ force: true });
        }
        callback();
    }


    //分部名选择事件
    partNameSelect = (value, option) => {
        this.props.form.setFieldsValue({ startIp: '', endIp: '' });
        this.setState({
            startIp: option.props.startIp,
            endIp: option.props.endIp
        })
    }

    validateSn = (rule, value, callback) =>{
        if(Utils.CheckSnFunc(value)){
            callback('序列号存在非法字符,请重新输入');
            return ;
        }
        callback();
        return;
    }

    validateVersion = (rule, value, callback) =>{
        if(Utils.CheckSnFunc(value)){
            callback('版本号存在非法字符,请重新输入');
            return ;
        }
        callback();
        return;
    }

    validatePreVersion = (rule, value, callback) =>{
        if(Utils.CheckSnFunc(value)){
            callback('旧版本号存在非法字符,请重新输入');
            return ;
        }
        callback();
        return;
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const { partNameData } = this.state;
        const partNameOptions = partNameData.map(d => <Option value={d.id} endIp={d.endIp} startIp={d.startIp} >{d.name}</Option>);
        let partState = sysCompany.id == 1;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 16,
                    offset: 8,
                },
            },
        };
        const IPLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 10 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };

        return (
            <div>
                <BreadcrumbCustom first={this.state.title} />
                {flag && <Form onSubmit={this.handleSubmit} style={{ marginTop: 40 }}>
                    {this.state.type !== 'mso' &&
                        <div>
                            <FormItem
                                {...formItemLayout}
                                label="通道号"
                            >
                                {getFieldDecorator('distNum')(
                                    <Input maxLength={255}/>
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="序列号"
                            >
                                {getFieldDecorator('sn',{
                                    rules: [{
                                        validator: this.validateSn
                                    }],
                                })(
                                    <Input maxLength={250}/>
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="版本号"
                            >
                                {getFieldDecorator('version',{
                                    rules: [{
                                        validator: this.validateVersion
                                    }],
                                })(
                                    <Input maxLength={250}/>
                                )}
                            </FormItem>
                        </div>}
                    {this.state.type == 'updateInstall' &&
                        <FormItem
                            {...formItemLayout}
                            label="旧版本号"
                        >
                            {getFieldDecorator('preVersion',{
                                rules: [{
                                    validator: this.validatePreVersion
                                }],
                            })(
                                <Input maxLength={250}/>
                            )}
                        </FormItem>
                    }
                    {partState && <FormItem
                        {...formItemLayout}
                        label="分部名"
                    >
                        {getFieldDecorator('partName',{
                            initialValue: sysCompany.id
                        })(
                            <Select
                                showSearch
                                style={{ width: '100%' }}
                                optionFilterProp="children"
                                onSelect={this.partNameSelect}
                                filterOption={true}
                            >
                                {partNameOptions}
                            </Select>
                        )}
                    </FormItem>}
                    <Row type="flex" justify="center">
                        <Col span={6}>
                            <FormItem
                                {...IPLayout}
                                label="IP段"
                            >
                                {getFieldDecorator('startIp', {
                                    initialValue: partState?"":sysCompany.startIp,
                                    rules: [{
                                        validator: this.checkStartIP
                                    }]
                                })(
                                    <Input maxLength={255}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={1} style={{ textAlign: 'center' }}>
                            <FormItem>
                                <label>-</label>
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem
                                {...IPLayout}
                            >
                                {getFieldDecorator('endIp', {
                                    initialValue: partState?"":sysCompany.endIp,
                                    rules: [{
                                        validator: this.checkEndIP
                                    }]
                                })(
                                    <Input maxLength={255}/>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <FormItem
                        {...formItemLayout}
                        label="时间"
                    >
                        {getFieldDecorator('range-picker', {
                            initialValue: [moment(currentDate, dateFormat), moment(currentDate, dateFormat)],
                            rules: [{
                                type: 'array', required: true, message: '请输入时间!'
                            }, {
                                validator: this.validateDate,
                            }]
                        })(
                            <RangePicker
                                allowClear={false}
                                style={{ width: '100%' }}
                                locale={locale}
                                format={dateFormat}
                                disabledDate={this.disabledDate}
                            />
                        )}
                    </FormItem>
                    <Row type="flex" justify="center">
                        <Col span={8}>
                            <FormItem {...tailFormItemLayout}>

                                <Button type="default" htmlType="submit">导出文件</Button>
                            </FormItem>

                        </Col>
                    </Row>
                </Form>}
                {!flag && <div>{Constant.STATISTICS_NO_PERMISSION}</div>}
            </div>
        );
    }
}

export default Form.create()(ExportForm);
